import fetch from 'dva/fetch';
import { routerRedux } from 'dva/router';
import Constants from "@/utils/constants";
import { getUrlParams } from '@/utils/tools';
import { clear } from '@/utils/localstorage';
import { Toast } from 'antd-mobile';
import NProgress from 'nprogress';

function checkStatus(response) {
  Toast.hide();
  if (response.status >= 200 && response.status < 300) {
    if (response.msg && response.msg.status === Constants.UNLOGIN_STATUS){
      logout();
      return;
    }
    return response.msg || true;
  } else if(response.status == 401) {
    logout();
  }else {
    throwError(response);
  }
}

function logout(){
  clear();
  global.location.href.indexOf('login') === -1 && global.dispatch(routerRedux.push({ pathname: '/login' }));
  if(window.logoutAlertInfo){
    return;
  }
  // window.logoutAlertInfo = Modal.info({
  //   title: '登陆过期，请重新登陆。',
  //   okText: '关闭',
  //   onOk() {
  //     window.logoutAlertInfo.destroy();
  //     window.logoutAlertInfo = null;
  //   },
  // });
}

function throwError(response) {
  if(response.status === Constants.UNLOGIN_STATUS){
    clear();
    global.dispatch(routerRedux.push({ pathname: '/login' }));
    return;
  }
  var info = {
    msg: response.msg,
    status: response.status
  }
  throw info;
}

function parseJSON(response) {
  // return response.json();
  return response.text().then((data)=>{
    if(typeof data === 'string' && data.indexOf('{') === -1){
      response.msg = data;
      return response;
    }
    if(data.length>0){
      response.msg = JSON.parse(data);
      return response;
    }else{
      return response;
    }
  }).catch(()=>{
    return response;
  })
}

/**
 * [filterUrlParams description]
 * @param  {[params]}  [description]
 * @return [String]    [过滤url的参数值为undefined、""等）]
 */
function filterUrlParams(path){
  let obj = getUrlParams(path);
  if(obj){
    let keys = Object.keys(obj);
    for(let i in keys){
      if(!obj[keys[i]] || obj[keys[i]] === "null"){
        // debugger;
        path = path.replace("&" + keys[i] + "=" + obj[keys[i]], "");
        path = path.replace(keys[i] + "=" + obj[keys[i]], "");
        path = path.replace("?&", "?");
      }
    }
  }
  return path;
}

function handleJsonToUrlCode(param, key){

  let paramStr="";

  if(global._.isString(param) || global._.isNumber(param) || global._.isBoolean(param)){

    paramStr+="&"+key+"="+encodeURIComponent(param);

  }else{
    const getKey = (key, i) => {
      // 当为数组且key为''时，getExtraBtnsOfActionType接口特殊处理
      if(key){
        return "."+i;
      }else{
        return i
      }
    }
    for(let i in param){
      // let k = key==null?i:key+(param instanceof Array?"["+i+"]":"."+i);
        // 数组特殊处理
        let k = key==null
        ?
        i
        :
        key+(param instanceof Array?"":getKey(key, i));
        paramStr+='&'+ handleJsonToUrlCode(param[i], k);
    }
  }

  return paramStr.substr(1);

};

function handleFetch(params){
  Toast.loading('Loading...', 0);
  // 允许get方法直接传url
  if (global._.isString(params)) {
    params = {'path': params};
  };
  // params.path = filterUrlParams(params.path);
  let time = new Date().getTime();
  let hash = '';
  if (params.path.indexOf('?') > -1) {
    hash = `&t=${time}`;
  } else {
    hash = `?t=${time}`;
  };
  params.path += hash;
  params.path = encodeURI(params.path);
  let option = {
    url: Constants.SERVER_URL + params.path,
    method: "GET",
    credentials: 'include',
    mode: 'cors',
    headers: {
      // "Content-Type": "application/json",
      "Content-Type": "application/x-www-form-urlencoded"
    }
  };
  // credentials有值时且“Content-Type"不能为 "application/json"，会发送预检请求，所以不能跨域
  // credentials是指带上cookie
  global._.merge(option, params);

  if (option.method.toUpperCase() === 'POST' || option.method.toUpperCase() === 'PUT') {
    option.headers['Content-Type'] = "application/x-www-form-urlencoded";
    if (option.body) {
      // option.body = JSON.stringify(option.body);
      console.log(option.body);
      option.body = handleJsonToUrlCode(option.body)
    }
  }

  return fetch(option.url, option)
    .then(parseJSON)
    .then(checkStatus)
}

export default handleFetch;
